#include"bob.h"
#include <stdlib.h>
#include<ctime>
#include <fstream>

bool BOB::prime_number(long x){
	for(int i=2; i<x; i++) 
		if( x%i == 0) return true;

	return false;
}

long BOB::NWD(long n, long m){
	while (n!=m) { 
		if (m>n) { m-=n; } 
		else { n-=m; } 
	} 
	return n;
}

long BOB::revers_number(long e, long f){
	for(int i=1; i<f; i++)
		if( ((e*i)%f) == 1 )
			return i;
}

long BOB::decode(){
	std::ifstream DATA;
	DATA.open("code.txt");
	long CODE;
	DATA >> CODE;
	DATA.close();

	//std::cout << "p" << p << " q" << q << " d" << d << " f" << f << " n" << n << std::endl;
	long tmp = CODE;
	for(int i=1; i<d; i++){
		tmp *= CODE;
		if(tmp>=n) tmp %= n;
	}
	return tmp;
} 

BOB::BOB(){
	srand ((int) time(NULL));
	do{
		//p = /*rand() % 100 + 1*/5;
		p = rand() % 100 + 1;
	}
	while(prime_number(p));
	do{
		//q = /*rand() % 100 + 1*/11;
		q = rand() % 100 + 1;
	}
	while(prime_number(p));

	n = p * q;
	f = (p-1)*(q-1);

	do{
		//e = /*rand() % 100 + 2*/23;
		do{
			e = rand() % n + 1;
		}
		while(prime_number(e));
	}
	while(NWD(f, e) != 1);

	d = revers_number(e, f);

	std::ofstream DATA("data.txt", std::ios::trunc);
	DATA << n << " " << e;

	DATA.close();
}